﻿#include "EditToolButton.h"

#include <QLineEdit>
#include <QEvent>
#include <QKeyEvent>
#include <QRegExpValidator>
#include <QRegExp>
#include <QDebug>

EditToolButton::EditToolButton(QWidget *parent)
    : QToolButton (parent)
    , m_lineEdit(new QLineEdit(this))
{
    this->setContextMenuPolicy(Qt::CustomContextMenu);
    m_lineEdit->hide();
    m_lineEdit->setPlaceholderText("请输入阈值:0<x<50");
    m_lineEdit->setValidator(new QRegExpValidator(QRegExp("^-?(255|[1,2]?[0-4]?\\d|[1,2]?5[0-4]?)$")));
    m_lineEdit->installEventFilter(this);
    m_lineEdit->setContextMenuPolicy(Qt::NoContextMenu);

    QObject::connect(this, &EditToolButton::customContextMenuRequested, this, [&]{
        m_lineEdit->setGeometry(this->rect());
        QToolButton::setText("");
        m_lineEdit->setPalette(this->palette());
        m_lineEdit->show();
        m_lineEdit->setFocus();
    });
}

void EditToolButton::setText(const QString &text)
{
    m_text = text;
    if (!m_lineEdit->isVisible())
        QToolButton::setText(m_text);
}

bool EditToolButton::eventFilter(QObject *obj, QEvent *ev)
{
    do {
        if (obj != m_lineEdit)
            break;

        if (ev->type() != QEvent::KeyPress)
            break;

        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);

        if (keyEvent->key() != Qt::Key_Enter && keyEvent->key() != Qt::Key_Return)
            break;

        const QString &text = m_lineEdit->text();
        qDebug() << "get text:" << text;
        if (!text.isEmpty())
            emit editTextChanged(text);

        m_lineEdit->hide();
        QToolButton::setText(m_text);
        m_lineEdit->clear();
    } while (false);

    QToolButton::eventFilter(obj, ev);
    return true;
}
